<script lang="ts" setup>
import type { VbenFormSchema } from '@vben/common-ui';

import { computed, markRaw } from 'vue';

import { AuthenticationLogin, SliderCaptcha, z } from '@vben/common-ui';
import { $t } from '@vben/locales';

import { loadAuthPredictApi } from '#/api';
import { useAuthStore } from '#/store';

import ThirdPartyLogin from './third-party-login.vue';

defineOptions({ name: 'Login' });

const authStore = useAuthStore();

async function usernameBlur(e: InputEvent) {
  const username = e.target.value;
  await loadAuthPredictApi({ username });
}

const formSchema = computed((): VbenFormSchema[] => {
  return [
    {
      component: 'VbenInput',
      componentProps: {
        placeholder: $t('authentication.usernameTip'),
        onBlur: usernameBlur,
      },
      fieldName: 'username',
      label: $t('authentication.username'),
      rules: z.string().min(1, { message: $t('authentication.usernameTip') }),
    },
    {
      component: 'VbenInputPassword',
      componentProps: {
        placeholder: $t('authentication.password'),
      },
      fieldName: 'password',
      label: $t('authentication.password'),
      rules: z.string().min(1, { message: $t('authentication.passwordTip') }),
    },
    {
      component: markRaw(SliderCaptcha),
      fieldName: 'captcha',
      rules: z.boolean().refine((value) => value, {
        message: $t('authentication.verifyRequiredTip'),
      }),
    },
  ];
});

async function doLogin(values: any) {
  const authenticationFactors = [
    { type: 'USERNAME', username: values.username, credential: values },
  ];
  authStore.authLogin(authenticationFactors);
}
</script>

<template>
  <AuthenticationLogin
    :form-schema="formSchema"
    :loading="authStore.loginLoading"
    @submit="doLogin"
  >
    <template #third-party-login>
      <ThirdPartyLogin />
    </template>
  </AuthenticationLogin>
</template>
